package com.kool.kmqtt.server.processer;

import com.kool.kmqtt.server.exception.ErrorCode;
import com.kool.kmqtt.server.exception.ProtocolException;
import com.kool.kmqtt.server.packet.Packet;
import com.kool.kmqtt.server.parser.PacketParser;
import com.kool.kmqtt.server.repository.RepositoryFactory;
import com.kool.kmqtt.server.session.SessionHolder;
import io.netty.channel.ChannelHandlerContext;

/**
 * DISCONNECT报文处理器
 */
public class DisconnectPacketProcessor extends PacketProcessor {
    public DisconnectPacketProcessor(ChannelHandlerContext ctx, PacketParser packetParser) {
        super(ctx, packetParser);
    }

    @Override
    protected void validate(Packet packet) {
        //所有的保留位都必须设置为0
        if (packet.getFixedHeader().getFlags() != 0) {
            throw new ProtocolException(ErrorCode.DISCONNECT_FLAGS_ERROR);
        }
    }

    @Override
    protected void processPacket(Packet packet) {
        String clientId = sessionContext.getClientId();
        //必须丢弃任何与当前连接关联的未发布的遗嘱消息
        repository.deleteWillStatus(clientId);

        //删除缓存中的会话上下文
        SessionHolder.getInstance().remove(sessionContext.getSessionId());
        if (sessionContext.getCleanSession() != null
                && sessionContext.getCleanSession()
                && sessionContext.getClientId() != null) {
            //删除会话状态
            RepositoryFactory.getRepository().deleteSessionStatus(sessionContext.getClientId());
        }
        if (sessionContext.getCtx() != null
                && sessionContext.getCtx().get() != null) {
            //断开网络连接
            sessionContext.getCtx().get().close();
        }
    }
}
